from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.contrib.auth import login as auth_login
from .models import *
from .forms import *
from django.contrib.auth.views import auth_login, auth_logout

# Create your views here.

def login(request):

    if request.method == "POST":
        lf = UserLoginForm(request.POST)
        if lf.is_valid():
            user = CustomUser.objects.filter(username=lf.cleaned_data['username']).first()
            if user:
                if user.check_password(lf.cleaned_data["password"]):

                    if user.is_active:

                        auth_login(request, user)

                        a = request.GET.get('next')
                        if a:
                            return redirect(a)

                        else:
                            return redirect(reverse('main:index'))
                    else:
                        lf.add_error('username', '用户未激活')
                        return render(request, 'user/login.html', {'form': lf})

                else:
                    lf.add_error("password", "密码错误")
                    return render(request, 'user/login.html', {"form": lf})
            else:
                lf.add_error("username","用户名不存在")
                return render(request, 'user/login.html', {"form": lf})

        else:
            return render(request, 'user/login.html', {"form": lf})

    else:
        lf = UserLoginForm()
        return render(request, 'user/login.html',{"form":lf})


def register(request):
    if request.method == "POST":
        rf = UserRegisterForm(request.POST)
        if rf.is_valid():
            user = rf.save(commit=False)
            user.set_password(rf.cleaned_data['password'])

            user.username = user.email
            user.is_active = False
            user.save()

            html = f'<a href = "http://127.0.0.1:8000/user/active/{user.id}"> 点击激活 </a>'
            send_mail("注册", "帮我注册", None, [user.email], html_message=html)
            return redirect(reverse('user:login'))

        else:
            return render(request, 'user/register.html', {"form": rf})
    else:
        rf = UserRegisterForm()
        return render(request, 'user/register.html',{"form":rf})

def active(request,id):
    user = CustomUser.objects.filter(id=id).first()
    if user:
        user.is_active = True
        user.save()
        return redirect(reverse('user:login'))
    else:
        HttpResponse("激活失败")

def logout(request):
    auth_logout(request)

    return redirect(reverse('user:login'))

@login_required()
def center(request):
    if request.method == 'POST':
        # ① 用 instance 保存，不要用 initial
        cuif = UserInfoChangeForm(data=request.POST, files=request.FILES, instance=request.user)
        if cuif.is_valid():
            # ② 保存用户信息
            user = cuif.save()
            print(f"头像保存成功: {user.head}")
            # ③ 重定向到个人中心并显示成功消息
            return redirect(reverse('user:center') + '?success=1')
        else:
            print(f"表单验证失败: {cuif.errors}")
        # ④ 校验失败继续走下面渲染，不用重新 new 表单
    else:
        cuif = UserInfoChangeForm(initial={"username": request.user.username})

    return render(request, 'user/center.html', {'form': cuif})
def change_password(request):
    if request.method == 'POST':
        cgf = UserPassWordChangeForm(request.POST)
        if cgf.is_valid():
            if request.user.check_password(cgf.cleaned_data['old_password']):
                request.user.set_password(cgf.cleaned_data['password'])
                request.user.save()

                # 修改密码从新登录
                auth_logout(request)
                return redirect(reverse('user:login'))


            else:
                cgf.add_error("old_password", "原始密码不正确")
                return render(request, 'user/change_password.html', {"form": cgf})
        else:
            return render(request, 'user/change_password.html', {"form": cgf})
    else:
        cgf = UserPassWordChangeForm()
        return render(request, 'user/change_password.html', {"form": cgf})


